from zipline.api import order, symbol, record, set_commission, order_value, order_target
from zipline.finance.commission import PerTrade

def initialize(context):
    # 设置参数
    context.period = 30  # 动量计算周期
    # 设置交易佣金
    set_commission(PerTrade(cost=0.001))

def handle_data(context, data):
    # 获取目标资产
    asset = symbol('AAPL')  # 示例资产，实际使用时替换
    
    # 获取历史价格数据
    prices = data.history(asset, 'close', context.period + 1, '1d')
    
    # 计算动量指标
    current_price = prices[-1]
    past_price = prices[0]  # period天前的价格
    momentum = (current_price / past_price) - 1
    
    # 获取当前持仓
    position = context.portfolio.positions[asset].amount
    
    # 交易逻辑
    if position == 0 and momentum > 0:  # 无持仓且正动量
        # 计算可买数量
        cash = context.portfolio.cash
        order_value(asset, cash)  # 全仓买入
    elif position > 0 and momentum < 0:  # 有持仓且负动量
        order_target(asset, 0)  # 清仓
    
    # 记录动量值
    record(momentum=momentum)